package com.xixi.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xixi.anno.Log;
import com.xixi.pojo.dto.LoginUserDTO;
import com.xixi.pojo.dto.UserDTO;
import com.xixi.pojo.query.UserQueryPage;
import com.xixi.pojo.vo.Result;
import com.xixi.pojo.vo.UserInfoVO;
import com.xixi.pojo.vo.UserVO;
import com.xixi.service.UserService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import com.xixi.utils.JwtTokenUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @GetMapping("/userList")
    public Result getUserlist(){
        List<UserVO> userVO = userService.list();
        return Result.success(userVO);
    }
    @GetMapping("/userById/{id}")
    public Result getUserById(@PathVariable Integer id){
        UserVO userVO = userService.getUserById(id);
        return Result.success(userVO);
    }
    @GetMapping("/page")
    public Result getUserPage(UserQueryPage userQueryPage){
        IPage<UserVO> userListVO = userService.getUserPage(userQueryPage);
        return Result.success(userListVO);
    }
    @Log
    @PostMapping("/insert")
    public Result insert(@RequestBody UserDTO userDTO){
        return userService.insert(userDTO);
    }
    @PostMapping("/register")
    public Result register(@RequestBody UserDTO userDTO){
        return userService.insert(userDTO);
    }
    @Log
    @PutMapping("/update")
    public Result update(@RequestBody UserDTO userDTO){
        return userService.update(userDTO);
    }
    @PostMapping("/code")
    public Result sendCode(@RequestParam("phone") String phone, HttpSession session){
        return userService.sendCode(phone,session);
    }
    @Log
    @DeleteMapping("/delete")
    public Result delete(@RequestParam List<Integer> ids){
        return userService.delete(ids);
    }

    @PostMapping("/userLogin")
    public Result login(@RequestBody LoginUserDTO loginUserDTO) {

        try {

            SecurityContextHolder.clearContext();

            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            loginUserDTO.getUsername(),
                            loginUserDTO.getPassword()
                    )
            );
            SecurityContextHolder.getContext().setAuthentication(authentication);
            String token = jwtTokenUtil.generateToken(loginUserDTO.getUsername());
            LoginUserDTO userDetails = userService.userLogin(loginUserDTO);
            if (userDetails != null) {
                UserInfoVO userInfo = new UserInfoVO();
                userInfo.setId(userDetails.getId());
                userInfo.setUsername(userDetails.getUsername());
                userInfo.setName(userDetails.getName());
                userInfo.setRole(userDetails.getRole());
                userInfo.setToken(token);
                return Result.success(userInfo);
            } else {
                SecurityContextHolder.clearContext();
                return Result.error("用户信息获取失败");
            }

        } catch (Exception e) {
            SecurityContextHolder.clearContext();
            return Result.error("用户名或密码错误");
        }
    }
}